#include "online_users_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"

namespace imserver {
namespace fcgi {

bool OnlineUsersRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }
  ParseKeyValue(body_.c_str(), "&", '=', &query_map_);

  std::stringstream rsp_stream;

  std::vector<int64_t> qids;
  std::vector<std::string> strs;
  boost::split(strs, GetQuery("ids"), boost::is_any_of(","),
      boost::token_compress_on);

  for (size_t i = 0; i < strs.size(); ++i) {
    int64_t qid = 0;
    try {
      qid = boost::lexical_cast<int32_t>(strs[i]);
    } catch (boost::bad_lexical_cast & e) {
      continue;
    }
    qids.push_back(qid);
  }

  std::map<int64_t, SessionType::type> online_map;
  if (!qids.empty()) {
    SessionAdapter::Instance().GetOnlineUsers(qids, &online_map);
  }

  rsp_stream << "Content-type: text/javascript; charset=utf-8\r\n\r\n";

  std::map<int64_t, SessionType::type>::const_iterator it = online_map.begin();
  rsp_stream << '[';
  int count = 0;
  for (; it != online_map.end(); ++it) {
    if (count++ > 0) {
      rsp_stream << ',';
    }
    rsp_stream << "{\"qid\":" << it->first
             << ",\"online\":" << it->second
             << '}';
  }
  rsp_stream << ']';


  LOG_DEBUG("OnlineUsersRequest " << body_ << " rsp=" << rsp_stream.str());
  FCGX_PutS(rsp_stream.str().c_str(), fcgi_out_);
  return true;
}

}
}


